package com.rightsidetech.trade.impl;


import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.MonthQueryRequest;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.dto.response.AdminHomeTopResp;
import com.rightsidetech.commom.dto.response.AgentHomeTopResp;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.DateUtil;
import com.rightsidetech.trade.dtos.request.*;
import com.rightsidetech.trade.dtos.response.*;
import com.rightsidetech.trade.dtos.response.HomeStoreSaleResp;
import com.rightsidetech.trade.entity.*;
import com.rightsidetech.trade.mapper.*;
import com.rightsidetech.trade.service.TdCommodityUserOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Transactional(rollbackFor = Exception.class)
@Service("tdCommodityUserOrderServiceImpl")
public class TdCommodityUserOrderServiceImpl implements TdCommodityUserOrderService {


    @Resource
    private TdCommodityUserOrderMapper tdCommodityUserOrderMapper;
    @Resource
    private TdCommodityOrderDetailsMapper tdCommodityOrderDetailsMapper;
    @Resource
    private TdCommodityTradeOrderMapper tdCommodityTradeOrderMapper;
    @Resource
    private TdCommodityAfterServiceRecordMapper tdCommodityAfterServiceRecordMapper;
    @Resource
    private TdBuyCarMapper tdBuyCarMapper;
    @Resource
    private TdBuyCarDetailMapper tdBuyCarDetailMapper;
    @Resource
    private TdCommodityUserGiftRecordMapper tdCommodityUserGiftRecordMapper;

    @Override
    public ResponseData<PageInfo<TdCommodityUserOrderResp>> page(TdCommodityOrderListRequest request) {
        PageHelper.startPage(request.getPageNo(), request.getPageSize());
        List<TdCommodityUserOrderResp> list = tdCommodityUserOrderMapper.list(request);

//        if (!StringUtils.isEmpty(list) && !list.isEmpty()) {
//            for (TdCommodityUserOrderResp tdCommodityUserOrderResp : list) {
//                if (tdCommodityUserOrderResp.getOrderStatus() == 1 || tdCommodityUserOrderResp.getOrderStatus() == 2) {
//                    int zpCount = tdCommodityOrderDetailsMapper.selectZpCountByOrderNo(tdCommodityUserOrderResp.getOrderNo());
//                    if (zpCount > 0) {
//                        tdCommodityUserOrderResp.setTrackFlag((byte) 1);
//                    }
//                }
//            }
//        }
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public ResponseData<PageInfo<TdCommodityUserOrderAgentResp>> agentPage(TdCommodityOrderListRequest request) {
        PageHelper.startPage(request.getPageNo(), request.getPageSize());
        List<TdCommodityUserOrderAgentResp> list = tdCommodityUserOrderMapper.listAgent(request);
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public List<TdCommodityUserOrderResp> selectList(TdCommodityOrderListRequest request) {
        return tdCommodityUserOrderMapper.list(request);
    }

    @Override
    public ResponseData<TdCommodityDetailResp> getByOrderId(Long id) {
        TdCommodityDetailResp tdCommodityDetailResp = tdCommodityUserOrderMapper.selectByOrderIdOrAgentId(id, null);
        if (StringUtils.isEmpty(tdCommodityDetailResp)) {
            return ResponseData.fail("找不到订单");
        }
        List<TdCommodityDetailMallResp> list = tdCommodityOrderDetailsMapper.listByOrderNo(tdCommodityDetailResp.getOrderNo(), null);
        tdCommodityDetailResp.setList(list);
        return ResponseData.success(tdCommodityDetailResp);

    }

    @Override
    public ResponseData<TdCommodityDetailResp> getByOrderIdAndAgentId(Long id, Long agentId) {
        TdCommodityDetailResp tdCommodityDetailResp = tdCommodityUserOrderMapper.selectByOrderIdOrAgentId(id, agentId);
        if (StringUtils.isEmpty(tdCommodityDetailResp)) {
            return ResponseData.fail("找不到订单");
        }
        List<TdCommodityDetailMallResp> list = tdCommodityOrderDetailsMapper.listByOrderNo(tdCommodityDetailResp.getOrderNo(), null);
        tdCommodityDetailResp.setList(list);
        return ResponseData.success(tdCommodityDetailResp);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData placeOrder(TdCommodityUserOrder tdCommodityUserOrder, List<TdCommodityOrderDetails> list, List<TdCommodityOrderDetails> list2, List<TdCommodityUserGiftRecord> list3, Long userInfoId) {

        int count = tdCommodityUserOrderMapper.insertSelective(tdCommodityUserOrder);

        for (TdCommodityOrderDetails orderDetails : list) {
            long parentId = orderDetails.getParentId();
            orderDetails.setParentId(0L);
            tdCommodityOrderDetailsMapper.insertSelective(orderDetails);
            for (TdCommodityOrderDetails orderDetails2 : list2) {
                if (orderDetails2.getParentId() == parentId) {
                    orderDetails2.setParentId(orderDetails.getId());
                    tdCommodityOrderDetailsMapper.insertSelective(orderDetails2);
                }
            }
        }
        for (TdCommodityUserGiftRecord giftRecord : list3) {
            tdCommodityUserGiftRecordMapper.insertSelective(giftRecord);
        }

        return ResponseData.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData updateOrder(String orderNo, String otherOrderNo, byte tradeChannel) {

        TdCommodityUserOrder tdCommodityUserOrder1 = tdCommodityUserOrderMapper.selectByOrderNo(orderNo);
        if (StringUtils.isEmpty(tdCommodityUserOrder1)) {
            return ResponseData.fail(CodeIdEnum.NonOrder);
        }
        TdCommodityUserOrder tdCommodityUserOrder = new TdCommodityUserOrder();
        tdCommodityUserOrder.setId(tdCommodityUserOrder1.getId());
        tdCommodityUserOrder.setUpdatedAt(new Date());
        tdCommodityUserOrder.setPayTime(new Date());
        if (tdCommodityUserOrder1.getOrderType() == 0) {
            tdCommodityUserOrder.setOrderStatus((byte) 1);
        } else {
            tdCommodityUserOrder.setOrderStatus((byte) 2);
            tdCommodityUserOrder.setFinishTime(new Date());
        }
        tdCommodityUserOrder.setTradeChannel(tradeChannel);

        int count = tdCommodityUserOrderMapper.updateByPrimaryKeySelective(tdCommodityUserOrder);
        if (count > 0) {
            //修改订单详情订单状态
            tdCommodityOrderDetailsMapper.updateOrderStatusByOrderNo(tdCommodityUserOrder.getOrderStatus(), orderNo, new Date());

            //添加资金记录
            TdCommodityTradeOrder tdCommodityTradeOrder = new TdCommodityTradeOrder();
            tdCommodityTradeOrder.setOrderNo(orderNo);
            tdCommodityTradeOrder.setThirdOrderNo(otherOrderNo);
            tdCommodityTradeOrder.setTradeChannel(tradeChannel);
            tdCommodityTradeOrder.setAmount(tdCommodityUserOrder1.getTotalAmount());
            tdCommodityTradeOrder.setDiscountAmount(tdCommodityUserOrder1.getDiscountAmount());
            tdCommodityTradeOrder.setActualAmount(tdCommodityUserOrder1.getActualAmount());
            tdCommodityTradeOrder.setOrderStatus((byte) 0);
            tdCommodityTradeOrder.setCreatedAt(new Date());
            int count1 = tdCommodityTradeOrderMapper.insertSelective(tdCommodityTradeOrder);
            if (count1 > 0) {
                return ResponseData.success(tdCommodityUserOrder1);
            }
        } else {
            return ResponseData.fail(CodeIdEnum.NonOrder);
        }

        return ResponseData.fail();
    }

    @Override
    public ResponseData updateOrderStatus(String orderNo) {

        TdCommodityUserOrder tdCommodityUserOrder = tdCommodityUserOrderMapper.selectByOrderNo(orderNo);
        TdCommodityUserOrder tdCommodityUserOrder1 = new TdCommodityUserOrder();
        tdCommodityUserOrder1.setId(tdCommodityUserOrder.getId());
        tdCommodityUserOrder1.setUpdatedAt(new Date());
        tdCommodityUserOrder1.setFinishTime(new Date());
        tdCommodityUserOrder1.setOrderStatus((byte) -1);
        tdCommodityUserOrder1.setRemarks("订单超时未支付自动关闭");

        int count = tdCommodityUserOrderMapper.updateByPrimaryKeySelective(tdCommodityUserOrder1);
        if (count > 0) {
            tdCommodityOrderDetailsMapper.updateOrderStatusAndTime(orderNo);
            return ResponseData.success();
        }
        return ResponseData.fail();
    }

    @Override
    public TdCommodityUserOrder findByOrderNo(String orderNo) {
        return tdCommodityUserOrderMapper.selectByOrderNo(orderNo);
    }

    @Override
    public ResponseData<PageInfo<TdCommodityAppOrderListResp>> findAppOrderByOrderStatus(TdCommodityUserAppListRequest req, Long userInfoId, String paramValue) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<TdCommodityAppOrderListResp> list = tdCommodityUserOrderMapper.selectAppList(req.getOrderStatus(), userInfoId);
        //判断售后时间是否到期
        Calendar c = Calendar.getInstance();

        for (TdCommodityAppOrderListResp resp : list) {
            if (resp.getOrderStatus().equals("1") || resp.getOrderStatus().equals("2")) {
                //判断是否超过售后有效期
                c.setTime(resp.getPayTime());
                c.add(Calendar.HOUR, Integer.parseInt(paramValue));
                if (c.getTime().getTime() < System.currentTimeMillis()) {
                    resp.setAfterServiceFlag((byte) 1);
                } else {
                    resp.setAfterServiceFlag((byte) 0);
                }
            }

            //查询商品列表
            List<TdCommodityAppOrderDetailResp> commodityList = tdCommodityOrderDetailsMapper.listAppByOrderNo(resp.getOrderNo(), "0");

            for (TdCommodityAppOrderDetailResp resp2 : commodityList) {
                //查询商品的赠品及换购商品
                List<TdCommodityDetailMallResp> commoditTagList = tdCommodityOrderDetailsMapper.selectAppTagByParentId(resp2.getId());
                resp2.setList(commoditTagList);
            }
            resp.setList(commodityList);
        }
        return ResponseData.success(new PageInfo<>(list));

    }

    @Override
    public PageInfo<TdCommodityStoreAppListResp> findOrderByStore(TdCommodityStoreAppListRequest req) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<TdCommodityStoreAppListResp> list = tdCommodityUserOrderMapper.selectStoreAppList(req);
        for (TdCommodityStoreAppListResp resp : list) {
            //查询商品列表
            List<TdCommodityAppOrderDetailResp> commodityList = tdCommodityOrderDetailsMapper.listAppByOrderNo(resp.getOrderNo(), "0");

            for (TdCommodityAppOrderDetailResp resp2 : commodityList) {
                //查询商品的赠品及换购商品
                List<TdCommodityDetailMallResp> commoditTagList = tdCommodityOrderDetailsMapper.selectAppTagByParentId(resp2.getId());
                resp2.setList(commoditTagList);
            }
            resp.setList(commodityList);
        }

        return new PageInfo<>(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData receiveOrder(String orderNo, Long storeId) {
/*        TdCommodityUserOrder tdCommodityUserOrder = tdCommodityUserOrderMapper.selectByOrderNo(orderNo);
        if (StringUtils.isEmpty(tdCommodityUserOrder)) {
            return ResponseData.fail(CodeIdEnum.NonOrder);
        }
        if (tdCommodityUserOrder.getStoreId() != storeId) {
            return ResponseData.fail("不是该门店的订单");
        }
        if (tdCommodityUserOrder.getOrderStatus() != 1) {
            return ResponseData.fail(CodeIdEnum.ErrorOrderStatus);
        }*/

        int count = tdCommodityUserOrderMapper.updateOrderStatusByOrderNo(orderNo, (byte) 2, new Date());
        if (count > 0) {
            int count2 = tdCommodityOrderDetailsMapper.updateOrderStatusByOrderNo((byte) 2, orderNo, new Date());
            return ResponseData.success("已接单，请及时上门服务");
        }
        return ResponseData.fail();
    }

    @Override
    public TdCommodityStoreOrderDetailResp findStoreOrderDetailByOrderNo(String orderNo, Long storeId, Long agentId) {
        TdCommodityStoreOrderDetailResp resp = tdCommodityUserOrderMapper.selectStoreDetailByOrderNo(orderNo, storeId, agentId);
        if (StringUtils.isEmpty(resp)) {
            return null;
        }

        //查询售后申请
        TdCommodityAfterServiceRecord tdAfterRecord = tdCommodityAfterServiceRecordMapper.selectLastByOrderNo(orderNo);
        if (!StringUtils.isEmpty(tdAfterRecord)) {
            resp.setApplyAt(tdAfterRecord.getCreatedAt());
            resp.setCheckedAt(tdAfterRecord.getCheckedAt());
            resp.setReason(tdAfterRecord.getReason());

/*            if (resp.getOrderStatus() == 1 || resp.getOrderStatus() == 2) {
                resp.setOrderStatus((byte) -2);
            }*/
        }

        //查询商品列表
        List<TdCommodityAppOrderDetailResp> commodityList = tdCommodityOrderDetailsMapper.listAppByOrderNo(resp.getOrderNo(), "0");

        for (TdCommodityAppOrderDetailResp resp2 : commodityList) {
            //查询商品的赠品及换购商品
            List<TdCommodityDetailMallResp> commoditTagList = tdCommodityOrderDetailsMapper.selectAppTagByParentId(resp2.getId());
            resp2.setList(commoditTagList);
        }
        resp.setList(commodityList);
        return resp;
    }

    @Override
    public ResponseData updateOrderAddress(String orderNo, String userName, String userPhone, String address, BigDecimal longitude, BigDecimal latitude) {
        TdCommodityUserOrder tdCommodityUserOrder = tdCommodityUserOrderMapper.selectByOrderNo(orderNo);
        if (StringUtils.isEmpty(tdCommodityUserOrder)) {
            return ResponseData.fail(CodeIdEnum.NonOrder);
        }
        if (tdCommodityUserOrder.getOrderStatus() != 0) {
            return ResponseData.fail(CodeIdEnum.ErrorOrderStatus);
        }
        //订单类型, 0-上门服务, 1-到店自取
        if (tdCommodityUserOrder.getOrderType() != 0) {
            return ResponseData.fail(CodeIdEnum.ErrorOrderType);
        }
        TdCommodityUserOrder td2 = new TdCommodityUserOrder();
        td2.setId(tdCommodityUserOrder.getId());
        td2.setUsName(userName);
        td2.setUsPhoneNo(userPhone);
        //if(req.getOrderType() == 0){
        td2.setUsAddress(address);
        td2.setLongitude(longitude);
        td2.setLatitude(latitude);
        //}
        td2.setUpdatedAt(new Date());

        int count = tdCommodityUserOrderMapper.updateByPrimaryKeySelective(td2);
        if (count > 0) {
            return ResponseData.success();
        }

        return ResponseData.fail();
    }

    @Override
    public ResponseData<TdCommodityAppOrderAfterServiceResp> findUserOrderByOrderNo(String orderNo, Long userInfoId, String paramValue) {
        TdCommodityAppOrderAfterServiceResp resp = tdCommodityUserOrderMapper.selectUsOderByOrderNo(orderNo, userInfoId);
        if (StringUtils.isEmpty(resp)) {
            return ResponseData.fail(CodeIdEnum.NonOrder);
        }

        //判断订单状态
        if (resp.getOrderStatus().equals("1") || resp.getOrderStatus().equals("2")) {
            Calendar c = Calendar.getInstance();
            //判断是否超过售后有效期
            c.setTime(resp.getPayTime());
            c.add(Calendar.HOUR, Integer.parseInt(paramValue));
            if (c.getTime().getTime() < System.currentTimeMillis()) {
                resp.setAfterServiceFlag((byte) 1);
            } else {
                resp.setAfterServiceFlag((byte) 0);
            }
        }

        //查询赠品邮寄地址
        TdCommodityUserGiftRecord giftRecord = tdCommodityUserGiftRecordMapper.selectOneByOrderNo(orderNo);
        if (!ObjectUtils.isEmpty(giftRecord)){
            resp.setGiftAddress(giftRecord.getGiftAddress());
        }

        TdCommodityAfterServiceRecord tdCommodityAfterServiceRecord = tdCommodityAfterServiceRecordMapper.selectLastByOrderNo(orderNo);
        if (!StringUtils.isEmpty(tdCommodityAfterServiceRecord)) {
            resp.setCheckStatus(tdCommodityAfterServiceRecord.getStatus());
            resp.setApplyAfterServiceAt(tdCommodityAfterServiceRecord.getCreatedAt());
            if (tdCommodityAfterServiceRecord.getStatus() == 1) {
                resp.setRefundAt(tdCommodityAfterServiceRecord.getUpdatedAt());
            }
        }


        //查询商品列表
        List<TdCommodityAppOrderDetailResp> commodityList = tdCommodityOrderDetailsMapper.listAppByOrderNo(resp.getOrderNo(), "0");

        for (TdCommodityAppOrderDetailResp resp2 : commodityList) {
            //查询商品的赠品及换购商品
            List<TdCommodityDetailMallResp> commoditTagList = tdCommodityOrderDetailsMapper.selectAppTagByParentId(resp2.getId());
            resp2.setList(commoditTagList);
        }
        resp.setList(commodityList);

        //查询物流单号
        List<String> trackNoList = tdCommodityUserGiftRecordMapper.selectTrackNoListByOrderNo(orderNo);
        if(CollUtil.isNotEmpty(trackNoList)){
            resp.setTrackNo(trackNoList);
        }

        return ResponseData.success(resp);
    }

    @Override
    public PageInfo<TdCommodityStoreAppListResp> storeOrderPage(TdCommodityAgentAppRequest req) {

        PageHelper.startPage(req.getPageNo(), req.getPageSize());

        List<TdCommodityStoreAppListResp> list = tdCommodityUserOrderMapper.selectAgentAppList(req);
        for (TdCommodityStoreAppListResp resp : list) {
            //查询商品列表
            List<TdCommodityAppOrderDetailResp> commodityList = tdCommodityOrderDetailsMapper.listAppByOrderNo(resp.getOrderNo(), "0");

            for (TdCommodityAppOrderDetailResp resp2 : commodityList) {
                //查询商品的赠品及换购商品
                List<TdCommodityDetailMallResp> commoditTagList = tdCommodityOrderDetailsMapper.selectAppTagByParentId(resp2.getId());
                resp2.setList(commoditTagList);
            }
            resp.setList(commodityList);
        }

        return new PageInfo<>(list);

    }

    @Override
    public TdCommodityAgentAppResp storeOrderStatis(Long agentId, Long storeId) {
        return tdCommodityUserOrderMapper.selectStatisByAgentId(agentId, storeId);
    }

    @Override
    public Long selectFinishTotalOrderNumByStoreId(Long storeId) {
        return tdCommodityUserOrderMapper.selectFinishTotalOrderNumByStoreId(storeId);
    }

    @Override
    public Long selectFinishTodayOrderNumByStoreId(Long storeId) {
        return tdCommodityUserOrderMapper.selectFinishTodayOrderNumByStoreId(storeId);
    }

    @Override
    public ResponseData cancelOrderByorderNo(String orderNo) {
        TdCommodityUserOrder tdCommodityUserOrder = tdCommodityUserOrderMapper.selectByOrderNo(orderNo);
        if (StringUtils.isEmpty(tdCommodityUserOrder)) {
            return ResponseData.fail(CodeIdEnum.NonOrder);
        }
        if (tdCommodityUserOrder.getOrderStatus() != 0) {
            return ResponseData.fail(CodeIdEnum.ErrorOrderStatus);
        }
        TdCommodityUserOrder tdCommodityUserOrder1 = new TdCommodityUserOrder();
        tdCommodityUserOrder1.setOrderStatus((byte) -1);
        tdCommodityUserOrder1.setId(tdCommodityUserOrder.getId());
        tdCommodityUserOrder1.setUpdatedAt(new Date());
        tdCommodityUserOrder1.setRemarks("用户取消订单");
        int count = tdCommodityUserOrderMapper.updateByPrimaryKeySelective(tdCommodityUserOrder1);
        if (count > 0) {
            tdCommodityOrderDetailsMapper.updateOrderStatusByOrderNo((byte) -1, orderNo, new Date());
            return ResponseData.success();
        }

        return ResponseData.fail();
    }

    @Override
    public ResponseData<PageInfo<TdCommodityAfterPageResp>> afterServicePage(TdCommodityAfterServiceReq req) throws Exception {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<TdCommodityAfterPageResp> list = tdCommodityAfterServiceRecordMapper.selectAfterServicePage(req);
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public List<TdCommodityAfterPageResp> selectAfterServiceList(TdCommodityAfterServiceReq req) throws Exception {
        return tdCommodityAfterServiceRecordMapper.selectAfterServicePage(req);
    }

    @Override
    public List<TdCommodityAfterServiceMoneyResp> selectAfterServiceMoneyList(TdCommodityAfterServiceMoneyReq req) {
        return tdCommodityAfterServiceRecordMapper.selectAfterServiceMoneyPage(req);
    }

    @Override
    public ResponseData<TdCommodityAfterServiceDetailResp> findAfterServiceDetailById(Long id) {
        TdCommodityAfterServiceDetailResp tdCommodityAfterServiceDetailResp = tdCommodityAfterServiceRecordMapper.selectAfterServiceDetail(id);
        if (StringUtils.isEmpty(tdCommodityAfterServiceDetailResp)) {
            return ResponseData.fail("找不到售后记录");
        }
        List<TdCommodityDetailMallResp> list = tdCommodityOrderDetailsMapper.listByOrderNo(tdCommodityAfterServiceDetailResp.getOrderNo(), null);
        tdCommodityAfterServiceDetailResp.setList(list);
        return ResponseData.success(tdCommodityAfterServiceDetailResp);
    }

    @Override
    public ResponseData updateOrderMsg(TdCommodityUpdateOrderMsgReq req, String storeName, Long agentId, String agentName, Long areaId, String areaName) {
        TdCommodityUserOrder tdCommodityUserOrder = tdCommodityUserOrderMapper.selectByOrderNo(req.getOrderNo());
        if (StringUtils.isEmpty(tdCommodityUserOrder)) {
            return ResponseData.fail(CodeIdEnum.NonOrder);
        }

        if (tdCommodityUserOrder.getSource() == 0) {
            return ResponseData.fail(CodeIdEnum.ErrorOrderSource);
        }

        TdCommodityUserOrder tdCommodityUserOrder1 = new TdCommodityUserOrder();
        tdCommodityUserOrder1.setId(tdCommodityUserOrder.getId());
        tdCommodityUserOrder1.setOrderStatus(req.getOrderStatus());
        if (!Objects.equals(tdCommodityUserOrder.getStoreId(), req.getStoreId())) {
            tdCommodityUserOrder1.setStoreId(req.getStoreId());
            tdCommodityUserOrder1.setStoreName(storeName);
        }
        if (!Objects.equals(tdCommodityUserOrder.getAgentId(), agentId)) {
            tdCommodityUserOrder1.setAgentId(agentId);
            tdCommodityUserOrder1.setAgentName(agentName);
        }
        if (!Objects.equals(tdCommodityUserOrder.getAreaId(), areaId)) {
            tdCommodityUserOrder1.setAreaId(areaId);
            tdCommodityUserOrder1.setAreaName(areaName);
        }
        tdCommodityUserOrder1.setUpdatedAt(new Date());
        int count = tdCommodityUserOrderMapper.updateByPrimaryKeySelective(tdCommodityUserOrder1);
        if (count > 0) {
            return ResponseData.success();
        }

        return ResponseData.fail();
    }

    @Override
    public List<TdCommodityOrderDetails> findOrderDetailByOrderNo(String orderNo) {
        return tdCommodityOrderDetailsMapper.findOrderDetailByOrderNo(orderNo);
    }

    @Override
    public AdminHomeTopResp orderStatis(Long areaId) {

        AdminHomeTopResp adminHomeTopResp = new AdminHomeTopResp();
        //销量 传1 为昨天
        Long yesterdaySale = tdCommodityOrderDetailsMapper.findSaleById(areaId, null, (byte) 1);
        Long totalSale = tdCommodityOrderDetailsMapper.findSaleById(areaId, null, null);
        adminHomeTopResp.setYesterdaySale(StringUtils.isEmpty(yesterdaySale) ? 0L : yesterdaySale);
        adminHomeTopResp.setTotalSale(StringUtils.isEmpty(totalSale) ? 0L : totalSale);

        //订单 传1 为昨天
        Long yesterdayOrderNum = tdCommodityUserOrderMapper.findOrderNumById(areaId, null, (byte) 1);
        Long totalOrderNum = tdCommodityUserOrderMapper.findOrderNumById(areaId, null, null);
        adminHomeTopResp.setYesterdayOrder(yesterdayOrderNum);
        adminHomeTopResp.setTotalOrder(totalOrderNum);

        return adminHomeTopResp;
    }

    @Override
    public List<HomeSpscSaleResp> todaySpecSale(Long areaId, Long agentId) {
        return tdCommodityOrderDetailsMapper.findTodaySpecSale(areaId, agentId);
    }

    @Override
    public List<HomeAgentSaleResp> todayAgentRanking(Long areaId) {
        return tdCommodityOrderDetailsMapper.selectTodayAgentRanking(areaId);
    }

    @Override
    public ResponseData<List<HomeMonthSaleResp>> monthSale(MonthQueryRequest request, Long areaId, Long agentId) {
        List<HomeMonthSaleResp> list = tdCommodityOrderDetailsMapper.findMonthSale(request.getStartTime(), request.getEndTime(), areaId, agentId);
        if (CollectionUtils.isEmpty(list)) {
            return ResponseData.success();
        }
        List<String> monthBetween = new ArrayList<>();
        if (!StringUtils.isEmpty(request.getStartTime()) && !StringUtils.isEmpty(request.getEndTime())) {
            monthBetween = DateUtil.getMonthBetween(request.getStartTime(), request.getEndTime());
        } else {
            monthBetween = DateUtil.getMonthBetween(DateUtil.getFirstMonth(), DateUtil.getDate(new Date()));
        }

        if (CollectionUtils.isEmpty(monthBetween)) {
            return ResponseData.success(list);
        }
        ArrayList<HomeMonthSaleResp> list1 = new ArrayList<>();
        for (String month : monthBetween) {
            HomeMonthSaleResp orderResp = new HomeMonthSaleResp();
            orderResp.setMonTime(month);
            orderResp.setSaleNum(0L);
            for (HomeMonthSaleResp resp : list) {
                if (resp.getMonTime().equals(month)) {
                    orderResp.setSaleNum(resp.getSaleNum());
                }
            }
            list1.add(orderResp);
        }
        return ResponseData.success(list1);
    }

    @Override
    public ResponseData<List<HomeMonthOrderResp>> monthOrder(MonthQueryRequest request, Long areaId) {
        List<HomeMonthOrderResp> list = tdCommodityUserOrderMapper.findMonthOrder(request.getStartTime(), request.getEndTime(), areaId);
        if (CollectionUtils.isEmpty(list)) {
            return ResponseData.success();
        }
        List<String> monthBetween = new ArrayList<>();
        if (!StringUtils.isEmpty(request.getStartTime()) && !StringUtils.isEmpty(request.getEndTime())) {
            monthBetween = DateUtil.getMonthBetween(request.getStartTime(), request.getEndTime());
        } else {
            monthBetween = DateUtil.getMonthBetween(DateUtil.getFirstMonth(), DateUtil.getDate(new Date()));
        }

        if (CollectionUtils.isEmpty(monthBetween)) {
            return ResponseData.success(list);
        }
        ArrayList<HomeMonthOrderResp> list1 = new ArrayList<>();
        for (String month : monthBetween) {
            HomeMonthOrderResp orderResp = new HomeMonthOrderResp();
            orderResp.setMonTime(month);
            orderResp.setOrderNum(0L);
            for (HomeMonthOrderResp resp : list) {
                if (resp.getMonTime().equals(month)) {
                    orderResp.setOrderNum(resp.getOrderNum());
                }
            }
            list1.add(orderResp);
        }
        return ResponseData.success(list1);
    }

    @Override
    public ResponseData<List<HomeMonthOrderResp>> thisMonthOrder(Long agentInfoId) {

        List<HomeMonthOrderResp> list = tdCommodityUserOrderMapper.findThisMonthOrderByAgentId(agentInfoId);
        if (CollectionUtils.isEmpty(list)) {
            return ResponseData.success();
        }
        //查询当月过去天数
        List<String> allDates = DateUtil.getAllDates(DateUtil.getFirstDay(), DateUtil.getDate(new Date()));
        if (CollectionUtils.isEmpty(allDates)) {
            return ResponseData.success(list);
        }
        ArrayList<HomeMonthOrderResp> list1 = new ArrayList<>();
        for (String day : allDates) {
            HomeMonthOrderResp monthOrderResp = new HomeMonthOrderResp();
            monthOrderResp.setMonTime(day);
            monthOrderResp.setOrderNum(0L);
            for (HomeMonthOrderResp orderResp : list) {
                if (orderResp.getMonTime().equals(day)) {
                    monthOrderResp.setOrderNum(orderResp.getOrderNum());
                    break;
                }
            }
            list1.add(monthOrderResp);
        }
        return ResponseData.success(list1);
    }

    @Override
    public List<TdBuyCarResp> selectByUserInfoId(Long userInfoId, Long storeId) {
        return tdBuyCarMapper.selectListByUserId(userInfoId, storeId);
    }

    @Override
    public List<TdBuyCarDetailResp> selectBuyCarDetailList(Long buyCarId, String commodityTag) {
        return tdBuyCarDetailMapper.selectListByBuyCarId(buyCarId, commodityTag);
    }

    @Override
    public List<TdBuyCarDetailDelResp> selectBuyCarDetailZPList(Long buyCarId, String commodityTag) {
        return tdBuyCarDetailMapper.selectZPListByBuyCarId(buyCarId, commodityTag);
    }

    @Override
    public List<TdBuyCarDetailZpResp> selectZPByBuyCarIdAndParentId(Long buyCarId, Long parentId) {
        return tdBuyCarDetailMapper.selectZpListByBuyCarIdAndParentId(buyCarId, parentId);
    }

    @Override
    public ResponseData delShoppingCarByMoreCondition(List<TdBuyCarDetail> tdBuyCarDetails, Long storeId, Long userInfoId) {
        List<Long> ids = new ArrayList<>();

        TdBuyCar tdBuyCar = tdBuyCarMapper.selectByUserInfoAndStoreId(userInfoId, storeId);
        if (StringUtils.isEmpty(tdBuyCar)) {
            return ResponseData.fail();
        }
        for (TdBuyCarDetail tdBuyCarDetail : tdBuyCarDetails) {
            List<Long> delList = tdBuyCarDetailMapper.selectIdsByManyCondition(tdBuyCar.getId(), tdBuyCarDetail.getCommodityId(), tdBuyCarDetail.getBuyType(), tdBuyCarDetail.getCommodityBarCode(), tdBuyCarDetail.getCommodityTag(), tdBuyCarDetail.getParentId());
            if (!StringUtils.isEmpty(delList) && !delList.isEmpty()) {
                ids.addAll(delList);
            }
        }
        if (ids.isEmpty()) {
            return ResponseData.fail();
        }

        int count = tdBuyCarDetailMapper.updateByIdList(ids);
        if (count > 0) {
            List<Long> tagIds = tdBuyCarDetailMapper.selectNoneParentIdByBuyCarId(tdBuyCar.getId());
            if (!StringUtils.isEmpty(tagIds) && !tagIds.isEmpty()) {
                tdBuyCarDetailMapper.updateByIdList(tagIds);
            }
            return ResponseData.success();
        }
        return ResponseData.fail();
    }

    @Override
    public ResponseData<PageInfo<TdCommodityBillResp>> findCommodityBillPage(TdCommodityBillReq req) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<TdCommodityBillResp> list = tdCommodityUserOrderMapper.listBill(req);
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public ResponseData<PageInfo<TdCommodityBillAgentResp>> findCommodityBillAgentPage(TdCommodityBillReq req) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<TdCommodityBillAgentResp> list = tdCommodityUserOrderMapper.listBillAgent(req);
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public List<HomeStoreSaleResp> todayStoreSale(Long agentInfoId) {
        return tdCommodityOrderDetailsMapper.listStoreSaleByAgentId(agentInfoId);
    }

    @Override
    public AgentHomeTopResp orderStatisByAgentId(Long agentInfoId) {

        AgentHomeTopResp agentHomeTopResp = new AgentHomeTopResp();
        //销量 传1 为昨天
        Long yesterdaySale = tdCommodityOrderDetailsMapper.findSaleById(null, agentInfoId, (byte) 1);
        Long totalSale = tdCommodityOrderDetailsMapper.findSaleById(null, agentInfoId, null);
        agentHomeTopResp.setYesterdaySale(StringUtils.isEmpty(yesterdaySale) ? 0L : yesterdaySale);
        agentHomeTopResp.setTotalSale(StringUtils.isEmpty(totalSale) ? 0L : totalSale);

        //订单 传1 为昨天
        Long yesterdayOrderNum = tdCommodityUserOrderMapper.findOrderNumById(null, agentInfoId, (byte) 1);
        Long totalOrderNum = tdCommodityUserOrderMapper.findOrderNumById(null, agentInfoId, null);
        agentHomeTopResp.setYesterdayOrder(yesterdayOrderNum);
        agentHomeTopResp.setTotalOrder(totalOrderNum);

        return agentHomeTopResp;
    }


    @Override
    public ResponseData insetTdCommodityList(List<TdCommodityUserOrder> orderList, List<TdCommodityOrderDetails> orderDetailsList) {
        if (null != orderList && !orderList.isEmpty()) {
            for (TdCommodityUserOrder td : orderList) {
                TdCommodityUserOrder td1 = tdCommodityUserOrderMapper.selectByOtherPaltformsOrderNo(td.getOtherPaltformsOrderNo());
                if (StringUtils.isEmpty(td1)) {
                    tdCommodityUserOrderMapper.insertSelective(td);
                } else {
                    TdCommodityUserOrder td2 = new TdCommodityUserOrder();
                    //boolean updateFlag = false;
                    td2.setId(td1.getId());
                    if (!td.getUsName().equals(td1.getUsName())) {
                        td2.setUsName(td.getUsName());
                        //updateFlag = true;
                    }
                    if (!td.getUsPhoneNo().equals(td1.getUsPhoneNo())) {
                        td2.setUsPhoneNo(td.getUsPhoneNo());
                        //updateFlag = true;
                    }
                    if (!td.getUsAddress().equals(td1.getUsAddress())) {
                        td2.setUsAddress(td.getUsAddress());
                        //updateFlag = true;
                    }
                    if (!td.getStoreName().equals(td1.getStoreName())) {
                        td2.setStoreName(td.getStoreName());
                        //updateFlag = true;
                    }
                    if (td.getCreatedAt().getTime() != td1.getCreatedAt().getTime()) {
                        td2.setCreatedAt(td.getCreatedAt());
                        //updateFlag = true;
                    }
                    if (td.getPayTime().getTime() != td1.getPayTime().getTime()) {
                        td2.setPayTime(td.getPayTime());
                        //updateFlag = true;
                    }
                    if (td.getTotalAmount().compareTo(td1.getTotalAmount()) != 0) {
                        td2.setTotalAmount(td.getTotalAmount());
                        //updateFlag = true;
                    }
                    if (td.getDiscountAmount().compareTo(td1.getDiscountAmount()) != 0) {
                        td2.setDiscountAmount(td.getDiscountAmount());
                        //updateFlag = true;
                    }
                    if (td.getActualAmount().compareTo(td1.getActualAmount()) != 0) {
                        td2.setActualAmount(td.getActualAmount());
                        //updateFlag = true;
                    }
                    if (!Objects.equals(td.getOrderType(), td1.getOrderType())) {
                        td2.setOrderType(td.getOrderType());
                        //updateFlag = true;
                    }
                    if (!td.getAgentName().equals(td1.getAgentName())) {
                        td2.setAgentName(td.getAgentName());
                        //updateFlag = true;
                    }
                    if (!td.getAreaName().equals(td1.getAreaName())) {
                        td2.setAreaName(td.getAreaName());
                        //updateFlag = true;
                    }
                    if (!Objects.equals(td.getSource(), td1.getSource())) {
                        td2.setSource(td.getSource());
                        //updateFlag = true;
                    }
                    td2.setLongitude(td.getLongitude());
                    td2.setLatitude(td.getLatitude());
                    //if (updateFlag) {
                    tdCommodityUserOrderMapper.updateByPrimaryKeySelective(td2);
                    //}
                    //删除原有的商品信息
                    tdCommodityOrderDetailsMapper.deletedByOrderNo(td1.getOrderNo());
                }
            }

            if (null != orderDetailsList && !orderDetailsList.isEmpty()) {
                for (TdCommodityOrderDetails details : orderDetailsList) {
                    tdCommodityOrderDetailsMapper.insertSelective(details);
                }
            }
        }
        return ResponseData.success();
    }

    @Override
    public ResponseData addZPShoppingCar(List<TdAddUpdateBuyCarDetailZPReq> zpList) {
        //取到该商品下的所有换购商品的id
        //取到传进来的商品id
        List<Long> ids = zpList.stream().map(TdAddUpdateBuyCarDetailZPReq::getId).filter(Objects::nonNull).collect(Collectors.toList());
        TdAddUpdateBuyCarDetailZPReq zp1 = zpList.get(0);
        List<Long> idsEd = tdBuyCarDetailMapper.selectZPIdsByParentId(zp1.getParentId());
        if (!StringUtils.isEmpty(idsEd) && !idsEd.isEmpty()) {
            if (!StringUtils.isEmpty(ids) && !ids.isEmpty()) {
                idsEd.removeAll(ids);
            }

            if (!StringUtils.isEmpty(idsEd) && !idsEd.isEmpty()) {
                tdBuyCarDetailMapper.updateByIdList(idsEd);
            }
        }

        List<TdBuyCarDetail> addTd = new ArrayList<>();
        List<TdBuyCarDetail> updateTd = new ArrayList<>();

        for (TdAddUpdateBuyCarDetailZPReq zpReq : zpList) {
            TdBuyCarDetail tdBuyCarDetail = new TdBuyCarDetail();
            BeanUtils.copyProperties(zpReq, tdBuyCarDetail);
            tdBuyCarDetail.setBuyType((byte) 0);

            TdBuyCarDetail tdBuyCarDetail2 = tdBuyCarDetailMapper.selectByPrimaryKey(zpReq.getParentId());
            if (StringUtils.isEmpty(tdBuyCarDetail2)) {
                return ResponseData.fail(CodeIdEnum.NONETDBUYCAR);
            }

            if (StringUtils.isEmpty(zpReq.getId()) || zpReq.getId() == 0) {
                tdBuyCarDetail.setCreatedAt(new Date());
                addTd.add(tdBuyCarDetail);
            } else {
                TdBuyCarDetail tdBuyCarDetail1 = tdBuyCarDetailMapper.selectByPrimaryKey(zpReq.getId());
                if (StringUtils.isEmpty(tdBuyCarDetail1)) {
                    return ResponseData.fail(CodeIdEnum.NONETDBUYCAR);
                }
                tdBuyCarDetail.setUpdatedAt(new Date());
                updateTd.add(tdBuyCarDetail);
            }
        }

        if (!addTd.isEmpty()) {
            for (TdBuyCarDetail tdBuyCarDetail : addTd) {
                tdBuyCarDetailMapper.insertSelective(tdBuyCarDetail);
            }
        }
        if (!updateTd.isEmpty()) {
            for (TdBuyCarDetail tdBuyCarDetai : updateTd) {
                tdBuyCarDetai.setUpdatedAt(new Date());
                tdBuyCarDetailMapper.updateByPrimaryKeySelective(tdBuyCarDetai);
            }
        }
        return ResponseData.success();
    }

    @Override
    public List<Long> selectZPIdsByParentId(Long parentId) {
        return tdBuyCarDetailMapper.selectZPIdsByParentId(parentId);
    }

    @Override
    public ResponseData<TdCommodityUserOrderZpResp> getOrderDetailTrackNo(String orderNo) {

        TdCommodityUserOrderZpResp tdCommodityUserOrderZpResp = tdCommodityUserOrderMapper.selectZPMsgByOrderNo(orderNo);
        if (StringUtils.isEmpty(tdCommodityUserOrderZpResp)) {
            return ResponseData.fail(CodeIdEnum.NonOrder);
        }

        List<TdCommodityUserOrderZpDetailResp> list = tdCommodityOrderDetailsMapper.selectZpDetailByOrderNo(orderNo);

        if (StringUtils.isEmpty(list) || list.isEmpty()) {
            return ResponseData.fail(CodeIdEnum.NoneZP);
        }

        tdCommodityUserOrderZpResp.setList(list);

        return ResponseData.success(tdCommodityUserOrderZpResp);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData updateTrackNoById(TdCommodityUpdateTrackNoReq req,Long loginId,String loginName) throws Exception {
        //校验订单是否存在
        TdCommodityUserGiftRecord giftRecord = tdCommodityUserGiftRecordMapper.selectByPrimaryKey(req.getId());
        if (null == giftRecord) {
            return ResponseData.fail(CodeIdEnum.NoneMallOrder);
        }

        giftRecord = new TdCommodityUserGiftRecord();
        giftRecord.setId(req.getId());
        giftRecord.setTrackNo(req.getTrackNo());
        giftRecord.setUpdatedAt(new Date());
        giftRecord.setUpdaterId(loginId);
        giftRecord.setUpdaterName(loginName);
        tdCommodityUserGiftRecordMapper.updateByPrimaryKeySelective(giftRecord);

        return ResponseData.success();
    }

    @Override
    public ResponseData delZpByParentId(Long parentId) {
        tdBuyCarDetailMapper.deleteByParentId(parentId);
        return ResponseData.success();
    }

    @Override
    public int updateTdCommodityUserOrder(TdCommodityUserOrder tdCommodityUserOrder) {
        return tdCommodityUserOrderMapper.updateByPrimaryKeySelective(tdCommodityUserOrder);
    }

    @Override
    public List<TdCommodityTradeOrderResp> findCommodityBillList(TdCommodityTradeOrderReq req) {
        return  tdCommodityTradeOrderMapper.listTradeOrder(req);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseData applyAfterService(TdCommodityApplyAfterServiceReq req, String paramValue, Long userInfoId) {
        TdCommodityUserOrder tdCommodityUserOrder = tdCommodityUserOrderMapper.selectByOrderNo(req.getOrderNo());
        if (StringUtils.isEmpty(tdCommodityUserOrder)) {
            return ResponseData.fail(CodeIdEnum.NonOrder);
        }
        //判断是否已经申请售后
        TdCommodityAfterServiceRecord tdCommodityAfterServiceRecord2 = tdCommodityAfterServiceRecordMapper.selectLastByOrderNo(req.getOrderNo());
        if (null != tdCommodityAfterServiceRecord2 && tdCommodityAfterServiceRecord2.getStatus() == 0) {
            return ResponseData.fail(CodeIdEnum.RepeatOrderAfterService);
        }

        //判断订单状态
        if (tdCommodityUserOrder.getOrderStatus() != 1 && tdCommodityUserOrder.getOrderStatus() != 2) {
            return ResponseData.fail(CodeIdEnum.ErrorOrderStatus);
        }
        //判断售后时间是否到期
        Calendar c = Calendar.getInstance();
        c.setTime(tdCommodityUserOrder.getPayTime());
        c.add(Calendar.HOUR, Integer.parseInt(paramValue));
        if (c.getTime().getTime() < System.currentTimeMillis()) {
            return ResponseData.fail(CodeIdEnum.ErrorOrderAfterService);
        }
        //统计商品数量
        Long commodityCount = tdCommodityOrderDetailsMapper.countByOrderNo(req.getOrderNo());

        TdCommodityAfterServiceRecord tdCommodityAfterServiceRecord = new TdCommodityAfterServiceRecord();
        tdCommodityAfterServiceRecord.setOrderNo(req.getOrderNo());
        tdCommodityAfterServiceRecord.setReason(req.getReason());
        tdCommodityAfterServiceRecord.setStatus((byte) 0);
        tdCommodityAfterServiceRecord.setCreatedAt(new Date());
        tdCommodityAfterServiceRecord.setCommodityCount(commodityCount);
        tdCommodityAfterServiceRecord.setAreaId(tdCommodityUserOrder.getAreaId());
        tdCommodityAfterServiceRecord.setAreaName(tdCommodityUserOrder.getAreaName());
        tdCommodityAfterServiceRecord.setAgentId(tdCommodityUserOrder.getAgentId());
        tdCommodityAfterServiceRecord.setAgentName(tdCommodityUserOrder.getAgentName());
        tdCommodityAfterServiceRecord.setStoreId(tdCommodityUserOrder.getStoreId());
        tdCommodityAfterServiceRecord.setStoreName(tdCommodityUserOrder.getStoreName());
        tdCommodityAfterServiceRecord.setUsName(tdCommodityUserOrder.getUsName());
        tdCommodityAfterServiceRecord.setUsPhoneNo(tdCommodityUserOrder.getUsPhoneNo());
        tdCommodityAfterServiceRecord.setUserInfoId(userInfoId);

        int count = tdCommodityAfterServiceRecordMapper.insertSelective(tdCommodityAfterServiceRecord);

        if (count > 0) {
            //修改订单状态
            TdCommodityUserOrder tdCommodityUserOrder1 = new TdCommodityUserOrder();
            tdCommodityUserOrder1.setId(tdCommodityUserOrder.getId());
            tdCommodityUserOrder1.setUpdatedAt(new Date());
            if (tdCommodityUserOrder.getOrderStatus() == 1) {
                tdCommodityUserOrder1.setOrderStatus((byte) 3);
            }
            if (tdCommodityUserOrder.getOrderStatus() == 2) {
                tdCommodityUserOrder1.setOrderStatus((byte) 4);
            }
            /*tdCommodityUserOrder1.setAfterServiceStatus((byte) 0);*/

            tdCommodityUserOrderMapper.updateByPrimaryKeySelective(tdCommodityUserOrder1);
            tdCommodityOrderDetailsMapper.updateOrderStatusByOrderNo(tdCommodityUserOrder1.getOrderStatus(), req.getOrderNo(), new Date());
            return ResponseData.success();
        }
        return ResponseData.fail();
    }

    @Override
    public ResponseData cancelAfterService(TdCommodityCancelReq req) {
        TdCommodityUserOrder tdCommodityUserOrder = tdCommodityUserOrderMapper.selectByOrderNo(req.getOrderNo());
        if (StringUtils.isEmpty(tdCommodityUserOrder)) {
            return ResponseData.fail(CodeIdEnum.NonOrder);
        }
        //判断订单状态
        if (tdCommodityUserOrder.getOrderStatus() != 3 && tdCommodityUserOrder.getOrderStatus() != 4) {
            return ResponseData.fail(CodeIdEnum.ErrorOrderStatus);
        }
        //取到最近的一条售后申请记录
        TdCommodityAfterServiceRecord tdCommodityAfterServiceRecord = tdCommodityAfterServiceRecordMapper.selectLastByOrderNo(req.getOrderNo());
        if (StringUtils.isEmpty(tdCommodityAfterServiceRecord)) {
            return ResponseData.fail(CodeIdEnum.NoneOrderAfterService);
        }

        //修改订单状态
        TdCommodityUserOrder tdCommodityUserOrder1 = new TdCommodityUserOrder();
        tdCommodityUserOrder1.setId(tdCommodityUserOrder.getId());
        tdCommodityUserOrder1.setUpdatedAt(new Date());
        if (tdCommodityUserOrder.getOrderStatus() == 3) {
            tdCommodityUserOrder1.setOrderStatus((byte) 1);
        }
        if (tdCommodityUserOrder.getOrderStatus() == 4) {
            tdCommodityUserOrder1.setOrderStatus((byte) 2);
        }
//        tdCommodityUserOrder1.setAfterServiceStatus((byte) -2);
        int count = tdCommodityUserOrderMapper.updateByPrimaryKeySelective(tdCommodityUserOrder1);
        tdCommodityOrderDetailsMapper.updateOrderStatusByOrderNo(tdCommodityUserOrder1.getOrderStatus(), req.getOrderNo(), new Date());

        if (count > 0) {
            //调整售后记录状态
            TdCommodityAfterServiceRecord tdCommodityAfterServiceRecord1 = new TdCommodityAfterServiceRecord();
            tdCommodityAfterServiceRecord1.setId(tdCommodityAfterServiceRecord.getId());
            tdCommodityAfterServiceRecord1.setStatus((byte) -2);
            tdCommodityAfterServiceRecord1.setUpdatedAt(new Date());
            int count2 = tdCommodityAfterServiceRecordMapper.updateByPrimaryKeySelective(tdCommodityAfterServiceRecord1);
            if (count2 > 0) {
                return ResponseData.success();
            }
        }
        return ResponseData.fail();
    }

    @Override
    public ResponseData checkAfterService(TdCheckAfterServiceReq req, Long storeId, Long storeLoginId, String storeLoginName) {
        TdCommodityUserOrder tdCommodityUserOrder = tdCommodityUserOrderMapper.selectByOrderNo(req.getOrderNo());
        if (StringUtils.isEmpty(tdCommodityUserOrder) || !Objects.equals(tdCommodityUserOrder.getStoreId(), storeId)) {
            return ResponseData.fail(CodeIdEnum.NonOrder);
        }
        //判断订单状态
        if (tdCommodityUserOrder.getOrderStatus() != 3 && tdCommodityUserOrder.getOrderStatus() != 4) {
            return ResponseData.fail(CodeIdEnum.ErrorOrderStatus);
        }

        //判断售后记录
        TdCommodityAfterServiceRecord tdCommodityAfterServiceRecord = tdCommodityAfterServiceRecordMapper.selectLastByOrderNo(req.getOrderNo());
        if (StringUtils.isEmpty(tdCommodityAfterServiceRecord)) {
            return ResponseData.fail(CodeIdEnum.NoneOrderAfterService);
        }

        //判断门店审核是否通过
        if (req.getStatus().equals("-1")) {
            //驳回, 修改订单状态, 修改售后记录
            //修改订单状态
            TdCommodityUserOrder tdCommodityUserOrder1 = new TdCommodityUserOrder();
            tdCommodityUserOrder1.setId(tdCommodityUserOrder.getId());
            tdCommodityUserOrder1.setUpdatedAt(new Date());
            if (tdCommodityUserOrder.getOrderStatus() == 3) {
                tdCommodityUserOrder1.setOrderStatus((byte) 1);
            }
            if (tdCommodityUserOrder.getOrderStatus() == 4) {
                tdCommodityUserOrder1.setOrderStatus((byte) 2);
            }
//            tdCommodityUserOrder1.setAfterServiceStatus((byte) -1);
            tdCommodityUserOrderMapper.updateByPrimaryKeySelective(tdCommodityUserOrder1);
            tdCommodityOrderDetailsMapper.updateOrderStatusByOrderNo(tdCommodityUserOrder1.getOrderStatus(), req.getOrderNo(), new Date());

            TdCommodityAfterServiceRecord tdCommodityAfterServiceRecord1 = new TdCommodityAfterServiceRecord();
            tdCommodityAfterServiceRecord1.setId(tdCommodityAfterServiceRecord.getId());
            tdCommodityAfterServiceRecord1.setStatus((byte) -1);
            tdCommodityAfterServiceRecord1.setUpdatedAt(new Date());
            tdCommodityAfterServiceRecord1.setCheckedAt(new Date());
            tdCommodityAfterServiceRecord1.setStoreLoginId(storeLoginId);
            tdCommodityAfterServiceRecord1.setStoreLoginName(storeLoginName);
            int count = tdCommodityAfterServiceRecordMapper.updateByPrimaryKeySelective(tdCommodityAfterServiceRecord1);
            if (count > 0) {
                return ResponseData.success();
            }
            return ResponseData.fail();
        }
        return ResponseData.success();
    }

    @Override
    public ResponseData agreeAfterService(TdCheckAfterServiceReq req, Long storeId, Long storeLoginId, String storeLoginName) {
        TdCommodityUserOrder tdCommodityUserOrder = tdCommodityUserOrderMapper.selectByOrderNo(req.getOrderNo());
        TdCommodityAfterServiceRecord tdCommodityAfterServiceRecord = tdCommodityAfterServiceRecordMapper.selectLastByOrderNo(req.getOrderNo());
        TdCommodityTradeOrder tdCommodityTradeOrder = tdCommodityTradeOrderMapper.selectByOrderNo(req.getOrderNo());

        //修改订单状态
        TdCommodityUserOrder tdCommodityUserOrder1 = new TdCommodityUserOrder();
        tdCommodityUserOrder1.setId(tdCommodityUserOrder.getId());
        tdCommodityUserOrder1.setUpdatedAt(new Date());
        tdCommodityUserOrder1.setOrderStatus((byte) 5);
        tdCommodityUserOrder1.setFinishTime(new Date());
//        tdCommodityUserOrder1.setAfterServiceStatus((byte) 1);

        tdCommodityUserOrderMapper.updateByPrimaryKeySelective(tdCommodityUserOrder1);
        tdCommodityOrderDetailsMapper.updateOrderStatusByOrderNo(tdCommodityUserOrder1.getOrderStatus(), req.getOrderNo(), new Date());

        TdCommodityTradeOrder tdCommodityTradeOrder1 = new TdCommodityTradeOrder();
        tdCommodityTradeOrder1.setId(tdCommodityTradeOrder.getId());
        tdCommodityTradeOrder1.setOrderStatus((byte) -1);
        tdCommodityTradeOrder1.setUpdatedAt(new Date());
        tdCommodityTradeOrderMapper.updateByPrimaryKeySelective(tdCommodityTradeOrder1);

        TdCommodityAfterServiceRecord tdCommodityAfterServiceRecord1 = new TdCommodityAfterServiceRecord();
        tdCommodityAfterServiceRecord1.setId(tdCommodityAfterServiceRecord.getId());
        tdCommodityAfterServiceRecord1.setStatus((byte) 1);
        tdCommodityAfterServiceRecord1.setUpdatedAt(new Date());
        tdCommodityAfterServiceRecord1.setCheckedAt(new Date());
        tdCommodityAfterServiceRecord1.setStoreLoginId(storeLoginId);
        tdCommodityAfterServiceRecord1.setStoreLoginName(storeLoginName);
        int count = tdCommodityAfterServiceRecordMapper.updateByPrimaryKeySelective(tdCommodityAfterServiceRecord1);
        if (count > 0) {
            return ResponseData.success();
        }
        return ResponseData.fail();
    }

    @Override
    public TdCommodityTradeOrder selectTradeOrderByOrderNo(String orderNo) {
        return tdCommodityTradeOrderMapper.selectByOrderNo(orderNo);
    }

    @Override
    public ResponseData addShoppingCar(TdCommodityBuyCardRequest req, Long userInfoId) {
        TdBuyCar tdBuyCar = tdBuyCarMapper.selectByUserInfoAndStoreId(userInfoId, req.getStoreId());
        boolean updateFlag = false;
        //购物车没东西
        if (StringUtils.isEmpty(tdBuyCar)) {
            return insertShoppingCar(req, userInfoId);
        }
        //购物车有数据
        for (TdCommodityBuyCardDetailRequest detailRequest : req.getList()) {
            TdBuyCarDetail tdBuyCarDetail3 = null;
            //更新赠品标识
            boolean b5 = false;
            if (req.getCarStatus() == 0) {
                tdBuyCarDetail3 = tdBuyCarDetailMapper.selectByPrimaryKey(detailRequest.getId());
                if (StringUtils.isEmpty(tdBuyCarDetail3)) {
                    return ResponseData.fail(CodeIdEnum.NONETDBUYCAR);
                }
                //判断新增还是更新购物车, 购物车状态, 0-更新商品数量, 1-新增商品数量
                TdBuyCarDetail tdBuyCarDetail2 = new TdBuyCarDetail();
                tdBuyCarDetail2.setId(tdBuyCarDetail3.getId());
                tdBuyCarDetail2.setUpdatedAt(new Date());
                //更新数量
                tdBuyCarDetail2.setCommodityNum(detailRequest.getCommodityNum());
                //判断规格,以旧换新,单件价格,编码 是否一样
                if ((StringUtils.isEmpty(tdBuyCarDetail3.getCommoditySpecs()) && !StringUtils.isEmpty(detailRequest.getCommoditySpecs())) || (!StringUtils.isEmpty(tdBuyCarDetail3.getCommoditySpecs()) && StringUtils.isEmpty(detailRequest.getCommoditySpecs()))) {
                    b5 = true;
                }

                if ((StringUtils.isEmpty(tdBuyCarDetail3.getCommodityBarCode()) && !StringUtils.isEmpty(detailRequest.getCommodityBarCode())) || (!StringUtils.isEmpty(tdBuyCarDetail3.getCommodityBarCode()) && StringUtils.isEmpty(detailRequest.getCommodityBarCode()))) {
                    b5 = true;
                }
                if ((StringUtils.isEmpty(tdBuyCarDetail3.getCommoditySpecs()) && StringUtils.isEmpty(detailRequest.getCommoditySpecs())) &&
                        (!tdBuyCarDetail3.getBuyType().equals(detailRequest.getBuyType()) || tdBuyCarDetail3.getCommodityPrice().compareTo(detailRequest.getCommodityPrice()) != 0)) {
                    b5 = true;
                }
                if (!StringUtils.isEmpty(tdBuyCarDetail3.getCommoditySpecs()) && !StringUtils.isEmpty(detailRequest.getCommoditySpecs())) {
                    if (!tdBuyCarDetail3.getCommoditySpecs().equals(detailRequest.getCommoditySpecs()) || !tdBuyCarDetail3.getBuyType().equals(detailRequest.getBuyType()) ||
                            !tdBuyCarDetail3.getCommodityTag().equals(detailRequest.getCommodityTag()) || tdBuyCarDetail3.getCommodityPrice().compareTo(detailRequest.getCommodityPrice()) != 0) {
                        b5 = true;
                    }
                }

                if ((!StringUtils.isEmpty(tdBuyCarDetail3.getCommodityBarCode()) && StringUtils.isEmpty(detailRequest.getCommodityBarCode())) ||
                        (StringUtils.isEmpty(tdBuyCarDetail3.getCommodityBarCode()) && !StringUtils.isEmpty(detailRequest.getCommodityBarCode()))) {
                    b5 = true;
                }
                if ((StringUtils.isEmpty(tdBuyCarDetail3.getCommodityBarCode()) && StringUtils.isEmpty(detailRequest.getCommodityBarCode())) &&
                        (!tdBuyCarDetail3.getBuyType().equals(detailRequest.getBuyType()) || tdBuyCarDetail3.getCommodityPrice().compareTo(detailRequest.getCommodityPrice()) != 0)) {
                    b5 = true;
                }

                if (!StringUtils.isEmpty(tdBuyCarDetail3.getCommodityBarCode()) && !StringUtils.isEmpty(detailRequest.getCommodityBarCode())) {
                    if (!tdBuyCarDetail3.getCommodityBarCode().equals(detailRequest.getCommodityBarCode()) || !tdBuyCarDetail3.getBuyType().equals(detailRequest.getBuyType()) ||
                            !tdBuyCarDetail3.getCommodityTag().equals(detailRequest.getCommodityTag()) || tdBuyCarDetail3.getCommodityPrice().compareTo(detailRequest.getCommodityPrice()) != 0) {
                        b5 = true;
                    }
                }


                //更新规格,以旧换新,单件价格,编码,图片
                tdBuyCarDetail2.setCommoditySpecs(detailRequest.getCommoditySpecs());
                tdBuyCarDetail2.setBuyType(detailRequest.getBuyType());
                tdBuyCarDetail2.setCommodityPrice(detailRequest.getCommodityPrice());
                tdBuyCarDetail2.setCommodityBarCode(detailRequest.getCommodityBarCode());
                tdBuyCarDetail2.setPicture(detailRequest.getPicture());
                tdBuyCarDetail2.setTypeId(detailRequest.getTypeId());

                if (b5) {
                    //判断购物车是否已经存在相同规格的商品
                    TdBuyCarDetail tdBuyCarDetail4 = tdBuyCarDetailMapper.selectByManyConditionExceptId(tdBuyCar.getId(), detailRequest.getCommodityId(), detailRequest.getBuyType(), detailRequest.getCommodityBarCode(), detailRequest.getCommodityTag(), 0L, tdBuyCarDetail2.getId());
                    if (!StringUtils.isEmpty(tdBuyCarDetail4)) {
                        //调整换购商品

                        tdBuyCarDetail2.setCommodityNum(tdBuyCarDetail2.getCommodityNum() + tdBuyCarDetail4.getCommodityNum());
                        tdBuyCarDetailMapper.deleteByPrimaryKey(tdBuyCarDetail4.getId());
                    }
                }
                tdBuyCarDetail2.setUpdatedAt(new Date());
                tdBuyCarDetailMapper.updateByPrimaryKeySelective(tdBuyCarDetail2);

            } else {
                tdBuyCarDetail3 = tdBuyCarDetailMapper.selectByManyCondition(tdBuyCar.getId(), detailRequest.getCommodityId(), detailRequest.getBuyType(), detailRequest.getCommodityBarCode(), (byte) 0, 0L);
                if (StringUtils.isEmpty(tdBuyCarDetail3)) {
                    tdBuyCarDetail3 = new TdBuyCarDetail();
                    BeanUtils.copyProperties(detailRequest, tdBuyCarDetail3);
                    tdBuyCarDetail3.setBuyCarId(tdBuyCar.getId());
                    tdBuyCarDetail3.setParentId(0L);
                    tdBuyCarDetail3.setCreatedAt(new Date());
                    tdBuyCarDetailMapper.insertSelective(tdBuyCarDetail3);

                } else {
                    //已经存在同款商品, 添加数量
                    TdBuyCarDetail tdBuyCarDetail2 = new TdBuyCarDetail();
                    tdBuyCarDetail2.setId(tdBuyCarDetail3.getId());
                    tdBuyCarDetail2.setUpdatedAt(new Date());

                    tdBuyCarDetail2.setCommodityNum(tdBuyCarDetail3.getCommodityNum() + detailRequest.getCommodityNum());

                    tdBuyCarDetailMapper.updateByPrimaryKeySelective(tdBuyCarDetail2);
                }
            }

            //判断是否存在 换购/赠品
/*            if (!StringUtils.isEmpty(detailRequest.getList()) && !b5) {
                for (TdCommodityBuyCardDetailZPRequest zpRequest : detailRequest.getList()) {
                    int count = tdBuyCarDetailMapper.selectCountByManyCondition(tdBuyCar.getId(), zpRequest.getCommodityId(), zpRequest.getBuyType(), zpRequest.getCommodityBarCode(), zpRequest.getCommodityTag(), tdBuyCarDetail3.getId());
                    if (count > 1) {
                        continue;
                    }

                    TdBuyCarDetail tdBuyCarDetailZP = tdBuyCarDetailMapper.selectByManyCondition(tdBuyCar.getId(), zpRequest.getCommodityId(), zpRequest.getBuyType(), zpRequest.getCommodityBarCode(), zpRequest.getCommodityTag(), tdBuyCarDetail3.getId());
                    if (StringUtils.isEmpty(tdBuyCarDetailZP)) {
                        tdBuyCarDetailZP = new TdBuyCarDetail();
                        BeanUtils.copyProperties(zpRequest, tdBuyCarDetailZP);
                        tdBuyCarDetailZP.setBuyCarId(tdBuyCar.getId());
                        tdBuyCarDetailZP.setParentId(tdBuyCarDetail3.getId());
                        tdBuyCarDetailZP.setCreatedAt(new Date());
                        tdBuyCarDetailMapper.insertSelective(tdBuyCarDetailZP);
                    } else {
                        //判断新增还是更新购物车, 购物车状态, 0-更新商品数量, 1-新增商品数量
                        TdBuyCarDetail tdBuyCarDetail2ZP = new TdBuyCarDetail();
                        tdBuyCarDetail2ZP.setId(tdBuyCarDetailZP.getId());
                        tdBuyCarDetail2ZP.setUpdatedAt(new Date());
                        if (req.getCarStatus() == 1) {
                            //新增
                            tdBuyCarDetail2ZP.setCommodityNum(tdBuyCarDetailZP.getCommodityNum() + zpRequest.getCommodityNum());
                        } else {
                            //更新数量
                            tdBuyCarDetail2ZP.setCommodityNum(zpRequest.getCommodityNum());
                        }
                        tdBuyCarDetailMapper.updateByPrimaryKeySelective(tdBuyCarDetail2ZP);
                    }
                }
            }*/
            updateFlag = true;
        }

        if (updateFlag) {
            TdBuyCar tdBuyCar2 = new TdBuyCar();
            tdBuyCar2.setId(tdBuyCar.getId());
            tdBuyCar2.setUpdatedAt(new Date());
            tdBuyCarMapper.updateByPrimaryKeySelective(tdBuyCar2);
        }
        return ResponseData.success();
    }

    @Override
    public ResponseData removeShoppingCar(List<Long> ids, Long userInfoId) {
        //判断是否是该用户的商品
        int count = tdBuyCarDetailMapper.selectCountByIdListAndUserInfoId(ids, userInfoId);
        if (ids.size() > count) {
            return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITY);
        }
        //删除商品
        int count2 = tdBuyCarDetailMapper.updateByIdList(ids);
        if (count2 > 0) {
            //清除没有商品的门店记录
            tdBuyCarMapper.updateNoneDetail();
            return ResponseData.success();
        }
        return ResponseData.fail();
    }

    public ResponseData insertShoppingCar(TdCommodityBuyCardRequest req, Long userInfoId) {
        TdBuyCar tdBuyCar = new TdBuyCar();
        tdBuyCar.setUserInfoId(userInfoId);
        tdBuyCar.setStoreId(req.getStoreId());
        tdBuyCar.setStoreName(req.getStoreName());
        tdBuyCar.setCreatedAt(new Date());
        tdBuyCar.setUpdatedAt(new Date());
        tdBuyCarMapper.insertSelective(tdBuyCar);

        for (TdCommodityBuyCardDetailRequest detailRequest : req.getList()) {
            TdBuyCarDetail tdBuyCarDetail = new TdBuyCarDetail();
            BeanUtils.copyProperties(detailRequest, tdBuyCarDetail);
            tdBuyCarDetail.setBuyCarId(tdBuyCar.getId());
            tdBuyCarDetail.setParentId(0L);
            tdBuyCarDetail.setCreatedAt(new Date());
            tdBuyCarDetail.setId(null);

            tdBuyCarDetailMapper.insertSelective(tdBuyCarDetail);

/*            if (!StringUtils.isEmpty(detailRequest.getList())) {
                for (TdCommodityBuyCardDetailZPRequest zpRequest : detailRequest.getList()) {
                    TdBuyCarDetail tdBuyCarDetailZP = new TdBuyCarDetail();
                    BeanUtils.copyProperties(zpRequest, tdBuyCarDetailZP);
                    tdBuyCarDetailZP.setBuyCarId(tdBuyCar.getId());
                    tdBuyCarDetailZP.setParentId(tdBuyCarDetail.getId());
                    tdBuyCarDetailZP.setCreatedAt(new Date());
                    tdBuyCarDetailMapper.insertSelective(tdBuyCarDetailZP);
                }
            }*/
        }
        return ResponseData.success();
    }


    @Override
    public List<TdCommodityOrderDetails> findCommodityByOrderNo(String orderNo, byte commodityTag) {
        return tdCommodityOrderDetailsMapper.findOrderDetailByOrderNoAndTag(orderNo, commodityTag);
    }

    @Override
    public TdBuyCar findTdBuyCarBybuyCarId(Long buyCarId) {
        return tdBuyCarMapper.selectByPrimaryKey(buyCarId);
    }

    @Override
    public TdBuyCarDetail findTdBuyCarDetailByParentId(Long parentId) {
        return tdBuyCarDetailMapper.selectByParentId(parentId);
    }

    @Override
    public TdBuyCarDetail findTdBuyCarDetailById(Long id) {
        return tdBuyCarDetailMapper.selectByPrimaryKey(id);
    }

    @Override
    public TdCommodityUserOrder selectByOtherPaltformsOrderNo(String otherPaltformsOrderNo) {
        return tdCommodityUserOrderMapper.selectByOtherPaltformsOrderNo(otherPaltformsOrderNo);
    }

    @Override
    public List<TdCommodityOrderDetails> findTdOrderDetailByParentId(Long parentId, byte commodityTag) {
        return tdCommodityOrderDetailsMapper.findOrderDetailByParentIdAndTag(parentId, (byte) 2);
    }

    public List<TdCommodityOrderDetails> detailsByOrder(String orderNo) {
        return tdCommodityOrderDetailsMapper.detailsByOrder(orderNo);
    }

    @Override
    public TdUserOrderInfoResp selectOrderById(Long id) {
        TdUserOrderInfoResp tdUserOrderInfoResp = tdCommodityUserOrderMapper.selectOrderById(id);
        if (!StringUtils.isEmpty(tdUserOrderInfoResp)) {
            List<String> comNameList = tdCommodityOrderDetailsMapper.findCommodityNameByOrderNo(tdUserOrderInfoResp.getOrderNo());
            if (!comNameList.isEmpty()) {
                tdUserOrderInfoResp.setCommName(comNameList.get(0));
            }
        }
        return tdUserOrderInfoResp;
    }

    @Override
    public void updateStoreNameByStoreId(Long storeId, String storeName) {
        tdBuyCarMapper.updateStoreNameByStoreId(storeName, storeId);
    }

    @Override
    public TdCommodityAppOrderAfterServiceResp selectByOrderNoAndUserInfoId(String orderNo, Long userInfoId) {
        return tdCommodityUserOrderMapper.selectUsOderByOrderNo(orderNo, userInfoId);
    }

    @Override
    public ResponseData<PageInfo<CommodityUserGiftResp>> giftPage(TdCommodityGiftOrderReq req) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<CommodityUserGiftResp> list = tdCommodityUserGiftRecordMapper.giftPage(req);
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public ResponseData<PageInfo<TdCommodityTradeOrderResp>> listTradeOrder(TdCommodityTradeOrderReq record) {
        PageHelper.startPage(record.getPageNo(),record.getPageSize());
        List<TdCommodityTradeOrderResp> tdCommodityTradeOrders = tdCommodityTradeOrderMapper.listTradeOrder(record);
        return ResponseData.success(new PageInfo<>(tdCommodityTradeOrders));
    }

    @Override
    public ResponseData<PageInfo<TdCommodityAfterServiceMoneyResp>> afterServiceMoneyPage(TdCommodityAfterServiceMoneyReq req) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<TdCommodityAfterServiceMoneyResp> list = tdCommodityAfterServiceRecordMapper.selectAfterServiceMoneyPage(req);
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public PageInfo<AppAfterSaleRecordResp> selectByStoreId(AppAfterSaleRecordReq req) {
        PageHelper.startPage(req.getPageNo(),req.getPageSize());
        List<AppAfterSaleRecordResp> appAfterSaleRecordResps = tdCommodityAfterServiceRecordMapper.selectByStoreId(req);
        return new PageInfo<>(appAfterSaleRecordResps);
    }

    @Override
    public UserAppAfterSaleRecordResp selectByUserInfoId(Long userInfoId) {
        return tdCommodityAfterServiceRecordMapper.selectByUserInfoId(userInfoId);
    }
}
